<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <link rel="icon" href="./Logo.jpg" type="image/x-icon">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的茶树 - 寻香</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link rel="stylesheet" href="common.css">
    <style>
        :root {
            --primary-color: #2d5a27;
            --secondary-color: #8ba888;
            --accent-color: #e8b059;
            --text-color: #333;
            --light-bg: #F8F1E4;
        }

        body {
            font-family: 'Arial', '微软雅黑', sans-serif;
            background: var(--light-bg);
            margin: 0;
            min-height: 100vh;
            padding: 20px;
            padding-top: 80px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        /* 茶树展示区域 */
        .tea-tree-container {
            background: white;
            border-radius: 20px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.1);
            text-align: center;
        }

        .tea-tree-image {
            width: 300px;
            height: 400px;
            margin: 20px auto;
            position: relative;
        }

        .tea-tree-image img {
            width: 100%;
            height: 100%;
            object-fit: contain;
        }

        /* 经验值进度条 */
        .experience-bar {
            background: #eee;
            height: 20px;
            border-radius: 10px;
            margin: 20px auto;
            max-width: 500px;
            position: relative;
            overflow: hidden;
        }

        .experience-progress {
            background: var(--primary-color);
            height: 100%;
            width: 0%;
            transition: width 0.5s ease;
            position: relative;
        }

        .experience-text {
            position: absolute;
            width: 100%;
            text-align: center;
            color: white;
            font-size: 12px;
            line-height: 20px;
            text-shadow: 0 0 2px rgba(0,0,0,0.5);
        }

        /* 茶树信息 */
        .tea-tree-info {
            margin: 20px 0;
            padding: 20px;
            background: #f8f8f8;
            border-radius: 10px;
        }

        .tea-tree-level {
            font-size: 24px;
            color: var(--primary-color);
            margin-bottom: 10px;
        }

        .tea-tree-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }

        .stat-item {
            background: white;
            padding: 15px;
            border-radius: 10px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.05);
        }

        /* 任务列表 */
        .tasks-container {
            background: white;
            border-radius: 20px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.1);
        }

        .task-list {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }

        .task-item {
            background: #f8f8f8;
            padding: 20px;
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .task-item:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .task-item.completed {
            background: #e8f5e9;
        }

        .task-reward {
            color: var(--accent-color);
            font-weight: bold;
            margin-top: 10px;
        }

        /* 奖励兑换区 */
        .rewards-container {
            background: white;
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.1);
        }

        .rewards-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }

        .reward-item {
            background: #f8f8f8;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
        }

        .reward-item:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .reward-image {
            width: 100px;
            height: 100px;
            margin: 0 auto 15px;
        }

        .reward-image img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 10px;
        }

        .reward-cost {
            color: var(--accent-color);
            font-weight: bold;
            margin-top: 10px;
        }

        .section-title {
            color: var(--primary-color);
            font-size: 24px;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid var(--primary-color);
        }
        
        /* 已认领茶树区域 */
        .adopted-trees {
            margin-top: 40px;
        }
        
        .adopted-tree {
            background: white;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
            display: flex;
            align-items: center;
        }
        
        .adopted-tree-image {
            width: 100px;
            height: 100px;
            border-radius: 10px;
            overflow: hidden;
            margin-right: 20px;
        }
        
        .adopted-tree-image img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .adopted-tree-info {
            flex: 1;
        }
        
        .adopted-tree-name {
            font-size: 1.2rem;
            color: var(--primary-color);
            margin-bottom: 5px;
        }
        
        .adopted-date, .expire-date {
            font-size: 0.9rem;
            color: #666;
            margin-bottom: 5px;
        }
        
        .renew-btn {
            background: var(--primary-color);
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 5px;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .renew-btn:hover {
            background: #1e4a1e;
        }
        
        .back-btn {
            display: inline-block;
            margin-bottom: 20px;
            padding: 10px 20px;
            background: var(--primary-color);
            color: white;
            text-decoration: none;
            border-radius: 5px;
            transition: all 0.3s;
        }
        
        .back-btn:hover {
            background: #1e4a1e;
        }
    </style>
</head>
<body>
    <div class="container">
        <a href="treefound.html" class="back-btn"><i class="fas fa-arrow-left"></i> 返回茶树认领</a>
        
        <!-- 茶树展示区域 -->
        <div class="tea-tree-container">
            <h2 class="section-title">我的茶树</h2>
            <div class="tea-tree-image">
                <img src="images/tree-level-1.svg" alt="茶树等级1" class="level-icon" id="teaTreeImage">
            </div>
            <div class="tea-tree-info">
                <div class="tea-tree-level">等级: <span id="treeLevel">1</span></div>
                <div class="experience-bar">
                    <div class="experience-progress" id="experienceProgress">
                        <div class="experience-text">0/100</div>
                    </div>
                </div>
                <div class="tea-tree-stats">
                    <div class="stat-item">
                        <h3>累计经验</h3>
                        <p id="totalExperience">0</p>
                    </div>
                    <div class="stat-item">
                        <h3>茶树品种</h3>
                        <p id="treeType">龙井</p>
                    </div>
                    <div class="stat-item">
                        <h3>成长天数</h3>
                        <p id="growthDays">1</p>
                    </div>
                    <div class="stat-item reward-info" style="background-color: #f8f4e6; padding: 10px; border-radius: 5px; margin-top: 10px; width: 100%;">
                        <h3 style="color: #d4b106;"><i class="fas fa-gift"></i> 10级奖励</h3>
                        <p style="color: #595959;">茶树达到10级可获得：<br>龙井茶树 - 500g龙井茶<br>铁观音茶树 - 800g铁观音茶</p>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 已认领茶树 -->
        <h2 class="section-title">我已认领的茶树</h2>
        <div id="adoptedTreesList" class="adopted-trees">
            <!-- 已认领茶树列表会通过JavaScript动态生成 -->
        </div>

        <!-- 任务列表 -->
        <div class="tasks-container">
            <h2 class="section-title">每日任务</h2>
            <div class="task-list" id="taskList">
                <!-- 任务项会通过JavaScript动态添加 -->
            </div>
        </div>

        <!-- 奖励兑换区 -->
        <div class="rewards-container">
            <h2 class="section-title">奖励兑换</h2>
            <div class="rewards-grid" id="rewardsGrid">
                <!-- 奖励项会通过JavaScript动态添加 -->
            </div>
        </div>
    </div>

    <script src="common.js"></script>
    <script>
        // 检查用户是否登录
        const currentUser = JSON.parse(localStorage.getItem('currentUser'));
        if (!currentUser) {
            window.location.href = 'user-auth.html';
        }

        // 获取用户数据
        const users = JSON.parse(localStorage.getItem('users')) || {};
        const user = users[currentUser.email];
        
        if (!user) {
            alert('用户数据错误，请重新登录');
            window.location.href = 'user-auth.html';
        }

        // 检查每日登录奖励
        const today = new Date().toDateString();
        if (user.teaTree && user.teaTree.lastLogin !== today) {
            user.teaTree.experience += 10;
            // 添加累计经验值
            if (!user.teaTree.totalExperience) {
                user.teaTree.totalExperience = (user.teaTree.level - 1) * 100 + user.teaTree.experience;
            } else {
                user.teaTree.totalExperience += 10;
            }
            user.teaTree.lastLogin = today;
            // 检查是否升级
            if (user.teaTree.experience >= 100) {
                user.teaTree.level += 1;
                user.teaTree.experience -= 100;
                // 不减少totalExperience，因为它是累计值
            }
            // 保存更新
            localStorage.setItem('users', JSON.stringify(users));
            alert('获得每日登录奖励：10点经验值！');
        }

        // 更新茶树显示
         function updateTeaTreeDisplay() {
            // 如果用户没有认领过茶树或没有茶树数据，显示提示信息
            if (!user.teaTree || !user.adoptedTrees || user.adoptedTrees.length === 0) {
                // 清空所有显示
                document.getElementById('treeLevel').textContent = '0';
                document.getElementById('teaTreeImage').style.display = 'none';
                document.getElementById('treeType').textContent = '未认领';
                document.getElementById('totalExperience').textContent = '0';
                document.getElementById('growthDays').textContent = '0';
                document.getElementById('experienceProgress').style.width = '0%';
                document.getElementById('experienceProgress').querySelector('.experience-text').textContent = '0/100';
                
                // 清空茶树容器并添加提示信息
                const treeContainer = document.querySelector('.tea-tree-container');
                treeContainer.innerHTML = `
                    <h2 class="section-title">我的茶树</h2>
                    <div class="empty-state" style="text-align: center; padding: 40px; background: #f9f9f9; border-radius: 15px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                        <img src="images/tree-level-1.svg" alt="空茶树" style="width: 150px; margin-bottom: 20px; opacity: 0.6;">
                        <h3 style="color: var(--primary-color); font-size: 1.5rem; margin-bottom: 15px;">您还没有认领茶树</h3>
                        <p style="color: #666; margin-bottom: 20px; line-height: 1.6;">认领一棵属于您的茶树，开启茶艺养成之旅！</p>
                        <a href="treefound.html" class="adopt-btn" style="display: inline-block; padding: 12px 30px; background: var(--primary-color); color: white; text-decoration: none; border-radius: 25px; font-weight: bold; transition: all 0.3s;">
                            <i class="fas fa-seedling" style="margin-right: 8px;"></i>去认领茶树
                        </a>
                    </div>
                `;
                return;
            }
            // 如果用户有茶树数据，则正常显示
            if (user.teaTree && user.adoptedTrees && user.adoptedTrees.length > 0) {
                const teaTree = user.teaTree;
                const adoptedTree = user.adoptedTrees[0];
                const level = teaTree.level;
                const exp = teaTree.experience;
                const maxExp = 100;
                
                // 如果没有totalExperience字段，添加它
                if (teaTree.totalExperience === undefined) {
                    teaTree.totalExperience = exp + (level - 1) * 100;
                    localStorage.setItem('users', JSON.stringify(users));
                }
                
                document.getElementById('treeLevel').textContent = level;
                // 根据茶树等级选择正确的图片
                document.getElementById('teaTreeImage').src = `images/tree-level-${level}.svg`;
                document.getElementById('teaTreeImage').style.display = 'block';
                document.getElementById('totalExperience').textContent = teaTree.totalExperience;
                document.getElementById('treeType').textContent = adoptedTree.type;
                
                // 正确计算成长天数
                const adoptDate = new Date(adoptedTree.adoptDate);
                const now = new Date();
                const growthDays = Math.floor((now - adoptDate) / (1000 * 60 * 60 * 24));
                document.getElementById('growthDays').textContent = growthDays > 0 ? growthDays : 0;
                
                const progress = (exp / maxExp) * 100;
                const progressBar = document.getElementById('experienceProgress');
                progressBar.style.width = `${progress}%`;
                progressBar.querySelector('.experience-text').textContent = `${exp}/${maxExp}`;
            }
        }
        
        // 渲染已认领的茶树
        function renderAdoptedTrees() {
            const adoptedTreesList = document.getElementById('adoptedTreesList');
            
            if (!user.adoptedTrees || user.adoptedTrees.length === 0) {
                adoptedTreesList.innerHTML = '<p>您还没有认领任何茶树，快去<a href="treefound.html">认领一棵茶树</a>吧！</p>';
                return;
            }
            
            const treeImages = {
                '龙井': '龙井.jpg',
                '铁观音': '铁观音.jpg',
                '普洱': '普洱茶.jpg'
            };
            
            const treeNames = {
                '1': '西湖龙井茶树',
                '2': '安溪铁观音茶树',
                '3': '云南普洱茶树'
            };
            
            adoptedTreesList.innerHTML = user.adoptedTrees.map(tree => {
                const adoptDate = new Date(tree.adoptDate);
                const expireDate = new Date(tree.expireDate);
                const now = new Date();
                const isExpired = expireDate < now;
                
                return `
                    <div class="adopted-tree">
                        <div class="adopted-tree-image">
                            <img src="${treeImages[tree.type]}" alt="${tree.type}茶树">
                        </div>
                        <div class="adopted-tree-info">
                            <div class="adopted-tree-name">${treeNames[tree.id]}</div>
                            <div class="adopted-date">认领日期: ${adoptDate.toLocaleDateString()}</div>
                            <div class="expire-date">到期日期: ${expireDate.toLocaleDateString()}</div>
                        </div>
                        <button class="renew-btn" data-tree-id="${tree.id}" ${isExpired ? '' : 'disabled style="background: #888;"'}>
                            ${isExpired ? '续约' : '有效期内'}
                        </button>
                    </div>
                `;
            }).join('');
            
            // 添加续约功能
            document.querySelectorAll('.renew-btn').forEach(btn => {
                if (!btn.disabled) {
                    btn.addEventListener('click', function() {
                        const treeId = this.getAttribute('data-tree-id');
                        renewTree(treeId);
                    });
                }
            });
        }
        
        // 续约茶树
        function renewTree(treeId) {
            const tree = user.adoptedTrees.find(t => t.id === treeId);
            if (tree) {
                const expireDate = new Date(tree.expireDate);
                tree.expireDate = new Date(expireDate.setFullYear(expireDate.getFullYear() + 1)).toISOString();
                
                // 保存更新
                localStorage.setItem('users', JSON.stringify(users));
                
                // 续约奖励
                user.teaTree.experience += 30;
                if (user.teaTree.experience >= 100) {
                    user.teaTree.level += 1;
                    user.teaTree.experience -= 100;
                }
                localStorage.setItem('users', JSON.stringify(users));
                
                alert('续约成功！获得30点经验值！');
                updateTeaTreeDisplay();
                renderAdoptedTrees();
            }
        }

        // 任务数据
        const tasks = [
            {
                id: 1,
                title: '每日登录',
                description: '登录网站获得奖励',
                reward: 10,
                type: 'daily'
            },
            {
                id: 2,
                title: '预约体验',
                description: '预约一次茶艺体验',
                reward: 20,
                type: 'once'
            },
            {
                id: 3,
                title: '分享体验',
                description: '分享您的茶艺体验心得',
                reward: 15,
                type: 'repeatable'
            },
            {
                id: 4,
                title: '购买茶叶',
                description: '购买任意茶叶商品',
                reward: 30,
                type: 'repeatable'
            }
        ];

        // 渲染任务列表
        function renderTasks() {
            const taskList = document.getElementById('taskList');
            taskList.innerHTML = tasks.map(task => `
                <div class="task-item" data-task-id="${task.id}">
                    <h3>${task.title}</h3>
                    <p>${task.description}</p>
                    <div class="task-reward">奖励: ${task.reward} 经验</div>
                </div>
            `).join('');

            // 添加任务点击事件
            taskList.querySelectorAll('.task-item').forEach(item => {
                item.addEventListener('click', () => completeTask(parseInt(item.dataset.taskId)));
            });
        }

        // 奖励数据
        const rewards = [
            {
                id: 1,
                title: '龙井茶样品',
                description: '精选龙井茶样品 50g',
                cost: 150,
                image: './images/龙井.jpg'
            },
            {
                id: 2,
                title: '茶艺体验券',
                description: '价值 100 元的茶艺体验券',
                cost: 300,
                image: './images/茶艺体验券.jpg'
            },
            {
                id: 3,
                title: '精美茶具',
                description: '传统手工茶具一套',
                cost: 500,
                image: './images/精美茶具.jpg'
            }
        ];

        // 渲染奖励列表
        function renderRewards() {
            const rewardsGrid = document.getElementById('rewardsGrid');
            rewardsGrid.innerHTML = rewards.map(reward => `
                <div class="reward-item" data-reward-id="${reward.id}">
                    <div class="reward-image">
                        <img src="${reward.image}" alt="${reward.title}">
                    </div>
                    <h3>${reward.title}</h3>
                    <p>${reward.description}</p>
                    <div class="reward-cost">所需经验: ${reward.cost}</div>
                </div>
            `).join('');

            // 添加奖励兑换事件
            rewardsGrid.querySelectorAll('.reward-item').forEach(item => {
                item.addEventListener('click', () => exchangeReward(parseInt(item.dataset.rewardId)));
            });
        }

        // 完成任务
        function completeTask(taskId) {
            const task = tasks.find(t => t.id === taskId);
            if (task) {
                // 增加经验值
                user.teaTree.experience += task.reward;
                user.teaTree.totalExperience += task.reward; // 更新累计经验值

                // 检查是否升级
                if (user.teaTree.experience >= 100) {
                    user.teaTree.level += 1;
                    user.teaTree.experience -= 100;
                    // 不减少totalExperience，因为它是累计值
                }

                // 保存用户数据
                localStorage.setItem('users', JSON.stringify(users));

                // 更新显示
                updateTeaTreeDisplay();

                // 显示完成提示
                alert(`恭喜完成任务！获得 ${task.reward} 点经验值！`);
            }
        }

        // 兑换奖励
        function exchangeReward(rewardId) {
            const reward = rewards.find(r => r.id === rewardId);
            if (reward) {
                if (user.teaTree.totalExperience >= reward.cost) {
                    user.teaTree.totalExperience -= reward.cost;
                    user.teaTree.experience -= reward.cost;
                    
                    // 如果经验值变为负数，需要从等级中扣除
                    while (user.teaTree.experience < 0 && user.teaTree.level > 1) {
                        user.teaTree.level -= 1;
                        user.teaTree.experience += 100;
                    }
                    
                    // 确保经验值不会小于0
                    if (user.teaTree.experience < 0) {
                        user.teaTree.experience = 0;
                    }
                    
                    localStorage.setItem('users', JSON.stringify(users));
                    updateTeaTreeDisplay();
                    alert(`恭喜兑换成功！已消耗 ${reward.cost} 点经验值。`);
                } else {
                    alert('经验值不足，无法兑换该奖励。');
                }
            }
        }

        // 初始化页面
        updateTeaTreeDisplay();
        renderAdoptedTrees();
        renderTasks();
        renderRewards();
        
        // 更新导航栏登录状态
        const authLink = document.getElementById('authLink');
        const logoutLink = document.getElementById('logoutLink');
    
        if (currentUser) {
            authLink.textContent = currentUser.username || '个人中心';
            authLink.href = '#';
            logoutLink.style.display = 'inline-block';
        }
        
        // 退出登录功能
        logoutLink.addEventListener('click', function(e) {
            e.preventDefault();
            localStorage.removeItem('currentUser');
            alert('您已成功退出登录');
            window.location.href = 'menu.html';
        });
    </script>
</body>
</html>